import ReactDOM from 'react-dom';
import React, { useEffect } from 'react';
import { HashRouter, Switch, Route, useHistory } from 'react-router-dom';

import RouterAnimate from '@/components/routerAnimate/RouterAnimate.jsx';

import { routes } from '@/router/router.js';

import '@/index.less';
// 热更新
if (module.hot) {
  module.hot.accept();
}
const routeFunc = (list) => {
  return list.map((route) => {
    return (
      <Route
        key={route.path}
        path={route.path}
        render={(props) => {
          const obj = route.params || {};
          if (obj.routerAnimation) {
            const Wrap = RouterAnimate(route.component);
            return (
              <Wrap {...obj} {...props}>
                {route.children && routeFunc(route.children)}
              </Wrap>
            );
          }

          return (
            <route.component {...obj} {...props}>
              {route.children && routeFunc(route.children)}
            </route.component>
          );
        }}
      ></Route>
    );
  });
};

const Root = (props) => {
  const history = useHistory();
  // console.log(history);
  useEffect(() => {
    if (history.location.pathname === '/') {
      history.replace('/index/home');
    }
  }, []);

  return props.children;
};

ReactDOM.render(
  <HashRouter>
    <Root>
      <Switch>{routeFunc(routes)}</Switch>
    </Root>
  </HashRouter>,
  document.getElementById('root')
);
